<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>数据权限管理</title>

	<jsp:include page="/common/init.jsp"></jsp:include>
	<link href="${ctx}/assets/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css" rel="stylesheet" />
	<script src="${ctx}/assets/zTree/js/jquery.ztree.all.js" type="text/javascript" charset="UTF-8"></script>
</head>
<body>
<div class="bg-white item_title">
	数据权限管理
</div>
<div class="bg-white">
	<div class="page-content case-info-content">
		<div class="row">
			<!-- 角色列表 -->
			<div class="col-xs-6">
				<div class="box">
					<div class="box-header" style="margin-bottom: 10px;">
						<span><h4><i class="fa fa-users"></i>站点列表</h4></span>
						
					</div>
					<div class="box-content">
					<%--<div class="self_table_search">--%>
				        <%--<label class="control-label"><span class="required">*</span>角色类型：</label>--%>
				        	<%--<select id="sflcSel" onchange="sflcChange();" class="form-control input-sm" >--%>
	                        	<%--<option value="">所有</option>--%>
	                            <%--<option value="1">流程角色</option>--%>
	                            <%--<option value="0">普通角色</option>--%>
	                        <%--</select>--%>
				    <%--</div>--%>
						<table id="wfRoleTable" class="table table-striped table-bordered self_table table-hover display">
						</table>
					</div>
				</div>
			</div>
			<!-- 授权用户列表 -->
			<div class="col-xs-6">
				<div class="box">
					<div class="box-header" style="height: 34px;margin-bottom: 10px;">
						<span><h4><i class="fa fa-user"></i> 已分配用户列表</h4></span>
						<div class="box-icon" style="float: right;">
							<button class="btn btn-md btn-primary" title="为当前角色组分配用户" id="btn_grantUsers" onclick="grantWfRoleUser()">
								<!--<i class="fa fa-users"></i> -->分配用户
							</button>
						</div>
					</div>
					<div class="box-content">
						<table id="wfRoleGrantUserTable" class="table self_table table-striped table-bordered bootstrap-datatable datatable">
						</table>
					</div>
				</div>
			</div>

		</div>
	</div>
</div>
	<!-- 流程角色编辑Modal -->
	<!-- 流程角色授权用户的Modal -->
	<div id="wfRoleGrantUserModel" class="modal fade opend_modal authorize_modal" data-backdrop="static">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<a data-dismiss="modal"><i class="fa fa-close"></i> </a>
					角色分配
				</div>
				<div class="modal-body">
					<ul id="wfRoleGrantUserTree" class="ztree"></ul>
				</div>
				<div class="modal-footer">
					<button type="submit" class="btn btn-md btn-success" onclick="grantUserToWfRole()"><i class="fa fa-save"></i> 保存</button>
					&nbsp;&nbsp;
					<button class="btn btn-md btn-default" data-dismiss="modal" aria-hidden="true"><i class="fa fa-close"></i> 取消</button>
				</div>
			</div>
		</div>
	</div>
	<script type="text/javascript">
        var path='<%=request.getContextPath() %>';
		// 注意：在一个界面上通过tableConf配置两个datatable时，配置项要保持相同（配置参数可不同）
		var wfroleSeltedData;
		var selWfroleID = '';
		var editMark = true;
		var grantWfRoleUserTree;

        function wfroleRowSeltListener() {
            var rows = $("#wfRoleTable tr");
            $.each(rows, function (index, row) {
                if (index > 0) {
                    $(row).click(function () {
                        wfroleSeltedData = $('#wfRoleTable').dataTable().fnGetData(this);
                        var role_id = selWfroleID = wfroleSeltedData.SITE_ID;
                        var roleName = wfroleSeltedData.SITE_NAME;
                        $(row).addClass("info");
                        $(row).siblings().removeClass("info");
                        // 更新右侧授权列表
                        $('#wfRoleGrantUserTable').dataTable().fnDraw();

                        //角色组名显示
                        $(".clickedRoleNameSpan").html("<strong>" + roleName + "</strong>");

                    });
                }
            });
        }

		function wfRolegrantUserRowSeltListener() {
			var rows = $("#wfRoleGrantUserTable tr");
			$.each(rows, function(index, row) {
				if (index > 0) {
					$(row).click(function() {
						$(row).addClass("info");
						$(row).siblings().removeClass("info");
					});
				}
			});
		}

		function showWfRequest() {
			return true;
		}

		function editWfRoleSuccessCallback(data) {
			if (data.success == true) {
				//$('#sysTable').hideLoading();  
				$('#wfRoleEditModel').modal('hide');
				$('#wfRoleTable').dataTable().fnDraw();
				notySuccess(data.message);
			} else {
				notyError(data.message);
			}
		}
		//部门树设置
		var grantWfRoleUserTreeSet = {
			view : {
				dblClickExpand : false,
				selectedMulti : false
			// 是否允许同时选中多个节点（默认true）
			},
			check : {
				enable : true
			// 节点上是否显示checkbox/radio
			},
			data : {
				key : {
					name : "NODE_NAME" // 节点名称的属性
				},
				simpleData : {
					enable : true, // 使用简单数据模型（array），但请注意simpleData内的参数（idKey，pIdKey，rootPId）满足父子关系
					idKey : "NODE_ID",
					pIdKey : "P_ID",
					rootPId : "-1"
				}
			},
			callback : {

			}
		};
		// 初始化树...
		function refreshGrantWfRoleUserTree() {
			try {
				//加载未授权人员树
				$.ajax({
					async : false,
					cache : false,
					type : 'POST',
					dataType : "json",
					url : path + "/role/getNoGrantUsers",
					data : {
						'SITE_ID' : selWfroleID
					},
					error : function(xhr, textStatus, exception) {
						notyError('未授权用户数据加载失败!' + xhr.responseText);
					},
					success : function(data) {
						if (grantWfRoleUserTree != null) {
                            grantWfRoleUserTree.destroy();
                        }
						grantWfRoleUserTree = $.fn.zTree.init($("#wfRoleGrantUserTree"),grantWfRoleUserTreeSet, data);
						// 展开根节点
						//grantWfRoleUserTree.expandAll(true);
						//grantWfRoleUserTree.expandNode(grantWfRoleUserTree.getNodeByParam("P_ID",'SHJC00K00Z00',null), true, false, false);
						grantWfRoleUserTree.expandNode(grantWfRoleUserTree.getNodeByParam("P_ID", '-1', null), true,false, false);
					}
				});
			} catch (e) {
				notyError(e);
			}
		}
		function grantWfRoleUser() {
			if (!wfroleSeltedData) {
				notyInfo('请选择一条记录');
				return;
			}
			$("#wfRoleGrantUserModel").modal('show');
			refreshGrantWfRoleUserTree();
		}
		// 添加未授权用户到角色
		function grantUserToWfRole() {
			// 检查授权用户项（至少一项）
			var checkNodesTmp = grantWfRoleUserTree.getCheckedNodes();
			if (checkNodesTmp.length == 0) {
				notyInfo('请先选择授权的用户(至少一项)...');
				return;
			}
			// 授权用户，存放入数组中
			var selGrantNodes = [];
			$.each(checkNodesTmp, function(index, node) {
				if (node.iconSkin == 'icon-user') {
					var nodeTmp = {
						'USER_ID' : node.NODE_ID
					};
					// node['XXX'] = value.XXX; // josn中存入其他对象
					selGrantNodes.push(nodeTmp); // 插入数组
				}
			});
			// 开始授权...
			if (selGrantNodes.length > 0) {
				// ajax用户授权
				var jsonObj = jQuery.parseJSON('{"SITE_ID":"' + selWfroleID + '"}');
				jsonObj['userIds'] = JSON.stringify(selGrantNodes);
				$.ajax({
					async : false,
					cache : false,
					type : 'POST',
					data : $.param(jsonObj),
					dataType : "json",
					url : path + "/user/batchGrantUserToWfRole",
					error : function() {
						notyError('系统用户授权为站点失败!');
					},
					success : function(data) {
						$('#wfRoleGrantUserTable').dataTable().fnDraw();
						$("#wfRoleGrantUserModel").modal('hide');
						notySuccess(data.message);
					}
				});
			} else {
				notyInfo('请先选择授权的用户(至少一项)...');
				return;
			}
		}

		// 界面初始化...
		$(function() {
			// 初始化流程角色列表
            $("#wfRoleTable").DataTable({
                "sDom" : "<'row-fluid'<'pull-left filterInput'f>>t<'row-fluid bgpage'<'span4'il><'span7'<'pull-right'p>>>",
                iDisplayStart: 0,
                iDisplayLength: 10,
				bAutoWidth: false,
                //"sScrollY": 450, //高度
                fnDrawCallback : wfroleRowSeltListener,
                sAjaxSource : path + "/user/getAllSite",//获取列表数据url
                oLanguage : {
                    "sSearch" : "站点名称："
                },
                "bSort": true,
                "order": [
                    [0, "asc"]
                ],
                //table 表头
                aoColumns: [
                    {'mDataProp':'SITE_ID' , 'sTitle' : '站点id','sClass' : 'center','bVisible' : false},
                    {'mDataProp':'SITE_NAME' ,'sTitle' : '站点名称','sClass' : 'center',"sDefaultContent" : "", 'sWidth' : '20%'},
                    {'mDataProp':'ADDRESS' ,'sTitle' : '站点地址','sClass' : 'center',"sDefaultContent" : "", 'sWidth' : '40%'}
                ],
                //渲染某列格式
                aoColumnDefs: [
                    {
                        aTargets: ["_all"],	//指向某一列，0为第一列
                        mRender: function (data, type, row) {
                            var subData = data;
                            if (data instanceof Object) {
                                try {
                                    return new Date(data.time).Format("yyyy-MM-dd hh:mm:ss");
                                } catch (e) {
                                    subData = data;
                                }
                            }
                            return subData;
                        }
                    }
                ],
                //向后台提交url携带的参数
                fnServerParams : function(aoData) {
                }
            });
			// 初始化流程角色已授权的用户列表
            $("#wfRoleGrantUserTable").DataTable({
                "sDom" : "<'row-fluid'<'pull-left filterInput'f>>t<'row-fluid bgpage'<'span4'il><'span7'<'pull-right'p>>>",
                iDisplayLength: 10,
				"bSort": false,
                //"sScrollY": 450, //高度
                fnDrawCallback : wfRolegrantUserRowSeltListener,
                sAjaxSource : path + "/user/getSiteGrantUsers",//获取列表数据url,
                oLanguage : {
                    "sSearch" : "用户/登录名："
                },
                //table 表头
                aoColumns: [
                    {'mDataProp':'USER_NAME' ,'sTitle' : '用户','sClass' : 'center',"sDefaultContent" : ""},
                    {'mDataProp':'LOGIN_ID' , 'sTitle' : '登录名','sClass' : 'center',"sDefaultContent" : ""},
                    {'mDataProp':'DUTY_NAME' ,'sTitle' : '职务','sClass' : 'center',"sDefaultContent" : ""},
                    {'mDataProp':'DEPT_NAME' ,'sTitle' : '部门','sClass' : 'center',"sDefaultContent" : ""},
                    {'mDataProp':'SITE_NAME' ,'sTitle' : '站点名','sClass' : 'center',"sDefaultContent" : ""},
                    {'mDataProp':'USER_ID' ,'sTitle' : '操作','sWidth': '60px','sClass' : 'center',"sDefaultContent" : ""}
                ],
                //渲染某列格式
                aoColumnDefs : [ {
                    "mRender" : function(data, type, row) {
                        var htmlCode = '<a href="javascript:;" title="从该角色组中移除" onclick="delApproveUser('
                            + row.USER_ID
                            + ',\''
                            + selWfroleID
                            + '\')">移除</a>';
                        return htmlCode;
                    },
                    "sClass" : "center",
                    "aTargets" : [ 5 ]
                }],
                //向后台提交url携带的参数
                fnServerParams : function(aoData) {
                    aoData.push({
                        "name" : "SITE_ID",
                        "value" : selWfroleID
                    });
                }
            });

            
			

		});

		function delApproveUser(USER_ID, SITE_ID) {
			if (!confirm("您是否要移除该记录？")) {
				return;
			}
			$.ajax({
				async : false,
				cache : false,
				type : 'POST',
				data : {
					'USER_ID' : USER_ID,
					'SITE_ID' : SITE_ID
				},
				dataType : "json",
				url : path + "/user/deleteSiteUser",
				error : function() {
					notyError('删除站点用户失败');
				},
				success : function(data) {
					$('#wfRoleGrantUserTable').dataTable().fnDraw();
					notySuccess(data.message);
				}
			});
		}
		
	</script>
</body>
</html>
